package com.wxcms.ctrl;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.wxcms.domain.Alert;
import com.wxcms.service.AlertService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.core.spring.SpringFreemarkerContextPathUtil;
import com.core.util.PropertiesConfigUtil;
import com.core.util.UploadUtil;
import com.wxapi.process.WxMemoryCacheClient;
import com.wxcms.domain.Account;
import com.wxcms.mapper.AccountDao;
import com.wxcms.mapper.MsgNewsDao;

/**
 * 
 */

@Controller
@RequestMapping("/wxcms")
public class WxCmsCtrl {

	@Autowired
	AccountDao accountDao;
	
	@Autowired
	MsgNewsDao msgNewsDao;

	@Autowired
	AlertService alertService;

	@RequestMapping(value = "/urltoken")
	public ModelAndView urltoken(String save){
		ModelAndView mv = new ModelAndView("wxcms/urltoken");
		List<Account> accounts = accountDao.listForPage(null);
		if(!CollectionUtils.isEmpty(accounts)){
			mv.addObject("account",accounts.get(0));
		}else{
			mv.addObject("account",new Account());
		}
		mv.addObject("cur_nav", "urltoken");
		if(save != null){
			mv.addObject("successflag",true);
		}
		return mv;
	}
	
	@RequestMapping(value = "/getUrl")
	public ModelAndView getUrl(HttpServletRequest request ,@ModelAttribute Account account){
		String path = SpringFreemarkerContextPathUtil.getBasePath(request);
		String url = request.getScheme() + "://" + request.getServerName() + path + "/wxapi/" + account.getAccount()+"/message.html";
		
		if(account.getId() == null){//新增
			account.setUrl(url);
			account.setToken(UUID.randomUUID().toString().replace("-", ""));
			account.setCreatetime(new Date());
			accountDao.add(account);
		}else{//更新
			Account tmpAccount = accountDao.getById(account.getId().toString());
			tmpAccount.setUrl(url);
			tmpAccount.setAccount(account.getAccount());
			tmpAccount.setAppid(account.getAppid());
			tmpAccount.setAppsecret(account.getAppsecret());
			tmpAccount.setMsgcount(account.getMsgcount());
			accountDao.update(tmpAccount);
		}
		WxMemoryCacheClient.addMpAccount(account);
		return new ModelAndView("redirect:/wxcms/urltoken.html?save=true");
	}
	
	@RequestMapping(value = "/ckeditorImage")
	public void ckeditorImage(HttpServletRequest request,HttpServletResponse response,@RequestParam(value="imgFile",required=false)MultipartFile file){
		String contextPath = SpringFreemarkerContextPathUtil.getBasePath(request);
		String url = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + contextPath;
		String realPath = request.getSession().getServletContext().getRealPath("/");
		
		//读取配置文上传件的路径
		if(PropertiesConfigUtil.getProperty("upload.properties","upload.path") != null){
			realPath = PropertiesConfigUtil.getProperty("upload.properties","upload.path").toString();
		}
		
		JSONObject obj = new JSONObject();
		if(file != null && file.getSize() > 0){
			String tmpPath = UploadUtil.doUpload(realPath,file);//上传文件，上传文件到 /res/upload/ 下
			obj.put("error", 0);
			obj.put("url", url + tmpPath);
		}
		
		try {
			response.getWriter().write(obj.toString());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	
	//上传永久素材，这里以图文消息为例子
	@RequestMapping(value = "/toUploadMaterial")
	public  ModelAndView toUploadMaterial(String[] newIds){
		ModelAndView mv = new ModelAndView("wxcms/materialUpload");
		mv.addObject("cur_nav", "material");
		return mv;
	}
	
	//到生成二维码页面
	@RequestMapping(value = "/qrcode")
	public ModelAndView qrcode(HttpServletRequest request){
		ModelAndView mv = new ModelAndView("wxcms/qrcode");
		mv.addObject("cur_nav", "qrcode");
		return mv;
	}
	
	//发送消息页面
	@RequestMapping(value = "/sendMsg")
	public ModelAndView sendMsg(HttpServletRequest request){
		ModelAndView mv = new ModelAndView("wxcms/sendmsg");
		mv.addObject("cur_nav", "sendmsg");
		
		return mv;
	}
	
	//通过interceptor处理OAuth认证
	@RequestMapping(value = "/oauthInterceptor")
	public ModelAndView oauthInterceptor(HttpServletRequest request){
		ModelAndView mv = new ModelAndView("wxcms/oauthInterceptor");
		mv.addObject("cur_nav", "oauthInterceptor");
		
		return mv;
	}
	
	//jssdk
	@RequestMapping(value = "/jssdk")
	public ModelAndView jssdk(HttpServletRequest request){
		ModelAndView mv = new ModelAndView("wxcms/jssdk");
		mv.addObject("cur_nav", "jssdk");
		
		return mv;
	}

	//jssdk
	@RequestMapping(value = "/alert")
	public ModelAndView alert(HttpServletRequest request,String id){
		ModelAndView mv = new ModelAndView("app/alert");
		Alert alert = alertService.getById(id);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
		List<Map<String,String>> list = new ArrayList<Map<String,String>>();
		Map<String,String> result = null;
		String alertDetail = alert.getDetail();
		if(alertDetail!=null&&!"".equals(alertDetail)){
			JSONObject detail = JSONObject.fromObject(alertDetail);
			Iterator<String> sIterator = detail.keys();
			if(sIterator.hasNext()){
				// 获得key
				String key = sIterator.next();
				// 根据key获得value, value也可以是JSONObject,JSONArray,使用对应的参数接收即可
				detail = detail.getJSONObject(key);
			}
			JSONArray hits = detail.getJSONArray("doc");
			for(int i=0;i<hits.size();i++){
				result = new HashMap<String,String>();
				JSONObject source = hits.getJSONObject(i);
				String errorInfo = source.getString("errorinfo");
				String time = source.getString("@timestamp");
				if(!"".equals(time)){
					Date date = new Date();
					date.setTime(Long.parseLong(time));
					time = sdf.format(date);
				}
				String name = "";
				if(source.containsKey("_dev")){
					JSONObject dev = source.getJSONObject("_dev");
					if (dev!=null) {
						if(dev.containsKey("name")){//编号
							name = dev.getString("name");
						}
					}
				}
				if(source.containsKey("_ext")){
					JSONObject ext = source.getJSONObject("_ext");
					if (ext!=null) {
						if(ext.containsKey("no")){//编号
							String no = ext.getString("no");
							result.put("no",no);
						}
						if(ext.containsKey("location")){//位置
							String location = ext.getString("location");
							result.put("location",location);
						}
						if(ext.containsKey("brand")){//品牌
							String brand = ext.getString("brand");
							result.put("brand",brand);
						}
						if(ext.containsKey("typename")){//型号
							String typename = ext.getString("typename");
							result.put("typename",typename);
						}
						if(ext.containsKey("adminname")){//负责人
							String adminname = ext.getString("adminname");
							result.put("adminname",adminname);
						}
						if(ext.containsKey("adminphone")){//负责人电话
							String adminphone = ext.getString("adminphone");
							result.put("adminphone",adminphone);
						}
						if(ext.containsKey("maintenance")){//负责人电话
							String maintenance = ext.getString("maintenance");
							result.put("maintenance",maintenance);
						}
						if(ext.containsKey("maintenancephone")){//负责人电话
							String maintenancephone = ext.getString("maintenancephone");
							result.put("maintenancephone",maintenancephone);
						}
						if(ext.containsKey("exp")){//负责人电话
							long exp = ext.getLong("exp");
							result.put("exp",sdf1.format(exp));
						}
					}
				}
				result.put("errorInfo",errorInfo);
				result.put("time",time);
				result.put("name",name);
				list.add(result);
			}
		}
		mv.addObject("detail", list);

		return mv;
	}

	@RequestMapping(value = "/500")
	public ModelAndView error500(HttpServletRequest request){
		ModelAndView mv = new ModelAndView("app/500");
		return mv;
	}

	@RequestMapping(value = "/404")
	public ModelAndView error404(HttpServletRequest request){
		ModelAndView mv = new ModelAndView("app/404");
		return mv;
	}
	
	
}
